package com.zizy.healthexpert.Adapter;
import android.R.color;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.zizy.healthexpert.Activity.FoodDetailActivity;
import com.zizy.healthexpert.Activity.MaterialDetailActivity;
import com.zizy.healthexpert.Activity.RecordFoodsActivity;
import com.zizy.healthexpert.Activity.SearchActivity;
import com.zizy.healthexpert.Config.Config;
import com.zizy.healthexpert.Database.MyDataBase_T_FOODS;
import com.zizy.healthexpert.Database.MyDataBase_T_FOODS_NUTRITION;
import com.zizy.healthexpert.Database.MyDatabase_Dishes;
import com.zizy.healthexpert.R;

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * Created by Zizy on 2014/5/11.
 * <p/>
 * this Adapter is for SearchActivity
 */
public class listResultAdapter extends ArrayAdapter {
    private Context context = null;
    private int res = 0;

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        final SearchFoodResult foodResult = (SearchFoodResult) getItem(position);//get one item
        LinearLayout linearLayout = (LinearLayout) View.inflate(context, res, null);//inflate
        TextView txtFoodName = (TextView) linearLayout.findViewById(R.id.txtFoodName);//find view by id
        Button btnMore = (Button) linearLayout.findViewById(R.id.btnMore);//find button

        final int id=foodResult.foodID;
        /*set color*/
        switch (foodResult.isGoodToEat){
            case Config.GOOD_TO_EAT:
                txtFoodName.setBackgroundColor(context.getResources().getColor(R.color.list_result_good_to_eat));
                break;
            case Config.CAN_NOT_EAT:
                txtFoodName.setBackgroundColor(context.getResources().getColor(R.color.list_result_can_not_to_eat));
                break;
            case Config.NOT_BAD_TO_EAT:
                txtFoodName.setBackgroundColor(context.getResources().getColor(R.color.list_result_not_bad_to_eat));
                break;
        }
        /*set icon*/
        switch (foodResult.foodType){
            case Config.MATERIAL:
                 Drawable drawable= context.getResources().getDrawable(R.drawable.icon_none);
                 drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                txtFoodName.setCompoundDrawables(drawable,null,null,null);
                break;

            case Config.DISHES:
                Drawable drawable2= context.getResources().getDrawable(R.drawable.icon_dishes);
                drawable2.setBounds(0, 0, drawable2.getMinimumWidth(), drawable2.getMinimumHeight());
                txtFoodName.setCompoundDrawables(drawable2,null,null,null);
                break;
        }
        /*set text*/
        txtFoodName.setText(foodResult.foodName);
        /*set button more click listener */
        btnMore.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                btnMoreClicked(id,foodResult.foodType,foodResult.isGoodToEat);
            }
        });
        /*set item click(txtFoodName) listener*/
        txtFoodName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listItemClicked(id,foodResult.foodType,foodResult.foodName,foodResult.isGoodToEat);
            }
        });

        return linearLayout;
    }
    /*listItemClicked*/
    public void listItemClicked(int foodID,int type,String foodName,int isGoodToEat){
        int mode=SearchActivity.mode;;//get mode( search activity's mode)

        if(mode==Config.SEARCH){
        /*if is Search mode*/ // ->open more
            btnMoreClicked(foodID,type,isGoodToEat);
        }else if(mode==Config.CHOOSE){
        /*if is Choose mode*/ // ->back to recordFoodsActivity
            switch(type){
                case Config.foodType.DISHES:{
                    String formattedNutString="";
                    HashMap<Integer,Double> nutMap=new HashMap<Integer, Double>();
                    String[] nutArray;
                    /*search database and get the field nutList*/ //nutList->1,222;
                    MyDatabase_Dishes myDatabaseDishes=new MyDatabase_Dishes(context);
                    ArrayList< Object > searchedDishes= (myDatabaseDishes.SearchDatabase("*",String.format("DishesID=%s",foodID)));
                    myDatabaseDishes.close();
                    MyDatabase_Dishes.FieldsDishes searchedDish=(MyDatabase_Dishes.FieldsDishes )searchedDishes.get(0);//found the dish,
                    String nutList="";

                    nutList=searchedDish.nutList;//TODO

                    nutArray=nutList.split(";");//1,222;
                    for (String nut:nutArray){
                        if(nut.equals("") ) continue;
                        int id= Integer.parseInt(nut.split(",")[0]);
                        double value= Double.parseDouble(nut.split(",")[1]);
                        if (nutMap.get(id) == null) {
                            nutMap.put(id, value);
                        } else {
                            nutMap.put(id, value + nutMap.get(id));
                        }
                    }
                    /*format*/
                    Set set = nutMap.entrySet();
                    for (Iterator iterator = set.iterator(); iterator.hasNext(); ) {
                        Map.Entry<Integer, Double> entry = (Map.Entry<Integer, Double>) iterator.next();
                        int id = entry.getKey();
                        double value = entry.getValue();
                        formattedNutString += id + "," + value + ";";
                    }
                    Config.recordFoodsActivity.viewItems.add(new listAddedDishesAdapter.addedDishes(foodName, Config.foodType.MATERIAL, formattedNutString));
                    context.startActivity(new Intent(context, RecordFoodsActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                    ((Activity) context).finish();
                    break;
                }
                case Config.foodType.MATERIAL: {
                    String formattedNutString = "";
                    /*get all nut. list*/
                        /*database*/
                    MyDataBase_T_FOODS_NUTRITION myDataBase_t_foods_nutrition = new MyDataBase_T_FOODS_NUTRITION(context);
                    ArrayList<MyDataBase_T_FOODS_NUTRITION.T_FOODS_NUTRITION> searchedList = myDataBase_t_foods_nutrition.SearchT_FOODS_NUTRITION("*", String.format("FOOD_ID= %s", foodID));
                    HashMap<Integer, Double> nutMap = new HashMap<Integer, Double>();
                    myDataBase_t_foods_nutrition.Close();
                    /*put in list*/
                    for (Iterator iterator = searchedList.iterator(); iterator.hasNext(); ) {
                        MyDataBase_T_FOODS_NUTRITION.T_FOODS_NUTRITION nut = (MyDataBase_T_FOODS_NUTRITION.T_FOODS_NUTRITION) iterator.next();
                        if (nutMap.get(nut.NUTRITION_ID) == null) {
                            nutMap.put(nut.NUTRITION_ID, nut.CONENT_VALUE);
                        } else {
                            nutMap.put(nut.NUTRITION_ID, nut.CONENT_VALUE + nutMap.get(nut.NUTRITION_ID));
                        }
                    }
                    /*format*/
                    Set set = nutMap.entrySet();
                    for (Iterator iterator = set.iterator(); iterator.hasNext(); ) {
                        Map.Entry<Integer, Double> entry = (Map.Entry<Integer, Double>) iterator.next();
                        int id = entry.getKey();
                        double value = entry.getValue();
                        formattedNutString += id + "," + value + ";";
                    }
                    Config.recordFoodsActivity.viewItems.add(new listAddedDishesAdapter.addedDishes(foodName, Config.foodType.MATERIAL, formattedNutString));
                    context.startActivity(new Intent(context, RecordFoodsActivity.class).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
                    break;
                }
                case Config.foodType.QR_FOOD: //now won't
                    break;
            }

        }


    }


    /*btnMore Clicked*/
    public void btnMoreClicked(int foodID,int type,int isGoodToEat){
        /*intent dishes detail*/


        Intent intent;
        switch (type){
            case Config.DISHES:
                intent=new Intent(context,FoodDetailActivity.class);
                break;
            case Config.MATERIAL:
                intent=new Intent(context,MaterialDetailActivity.class);
                break;
            default:
                intent=new Intent(context,FoodDetailActivity.class);
                break;
        }
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("foodID", foodID);
        intent.putExtra("isGoodToEat", isGoodToEat);
        context.startActivity(intent);

    }
    public listResultAdapter(Context context, int resource, List objects) {
        super(context, resource, objects);
        this.context = context;
        this.res = resource;
    }


    static  public class SearchFoodResult {
        String foodName = "";
        int isGoodToEat = Config.GOOD_TO_EAT;
        int foodID=0;
        int foodType=Config.DISHES;
        /**
         * @param foodName      食物名字
         * @param isGoodToEat   是不是可以吃 參照Config文件中的定義常數
         * @param foodID        id
         * @param foodType      參照Config 料理 或者是 食材
         */
        public SearchFoodResult(String foodName, int isGoodToEat, int foodID, int foodType) {
            this.foodName = foodName;
            this.isGoodToEat = isGoodToEat;
            this.foodID = foodID;
            this.foodType = foodType;
        }
    }

}
